package com.zymail.controller;

import com.zymail.service.ex.*;
import com.zymail.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
/** 控制器类的基类 */
public class BaseController {
    @Autowired
    StringRedisTemplate redisTemplate;

    /** 操作成功的状态码 */
    public static final int OK = 200;

    /** @ExceptionHandler用于统一处理方法抛出的异常 */
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<Void>(e);
        if (e instanceof UsernameDuplicateException) {
            result.setState(4000);
        } else if (e instanceof UserNotFoundException) {
            result.setState(4001);
        } else if (e instanceof PasswordNotMatchException) {
            result.setState(4002);
        } else if (e instanceof InsertException) {
            result.setState(5000);
        }
        return result;
    }

    /**
     * 从HttpSession对象中获取adminId
     * @param session HttpSession对象
     * @return 当前登录的用户的id
     */
    protected final Integer getAdminIdFromSession(HttpSession session) {
        return Integer.valueOf(session.getAttribute("adminId").toString());
    }

    /**
     * 从HttpSession对象中获取管理员名字
     * @param session HttpSession对象
     * @return 当前登录的用户名
     */
    protected final String getAdminNameFromSession(HttpSession session) {
        return session.getAttribute("adminName").toString();
    }

    /**
     * session_key -> userId
     * @param session_key session_key
     * @return  userid
     */
    protected Integer get_userId(String session_key){
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String userId = operations.get(session_key);
        if(userId == null){return 0;}
        return Integer.parseInt(userId);
    }
}
